<template>
  <div class="upload-page">
    <Header />
    
    <div class="container">
      <el-card class="upload-card">
        <div slot="header" class="clearfix">
          <span>上传参赛作品</span>
          <span v-if="registrationNumber" class="registration-label">报名编号: {{ registrationNumber }}</span>
        </div>
        
        <div class="registration-info" v-if="registrationNumber">
          <el-alert
            title="您已完成报名，请上传参赛作品"
            type="success"
            :closable="false"
            show-icon>
            <p>请根据您的参赛类型上传作品，手机摄影或相机摄影作品。</p>
          </el-alert>
        </div>
        
        <div class="registration-info" v-else>
          <el-alert
            title="尚未完成报名"
            type="warning"
            :closable="false"
            show-icon>
            <p>您尚未完成报名，建议先完成报名流程。</p>
            <el-button type="primary" size="small" @click="goToContest">去报名</el-button>
          </el-alert>
        </div>
        
        <el-divider content-position="center">作品信息</el-divider>
        
        <el-form :model="photoForm" :rules="photoRules" ref="photoForm" label-width="100px" class="upload-form">
          <el-form-item label="作品图片" prop="file" class="upload-item">
            <div class="manual-upload">
              <input 
                type="file" 
                ref="fileInput" 
                style="display: none" 
                accept="image/jpeg,image/png"
                @change="handleFileChange"
              />
              <div 
                class="upload-box" 
                @click="$refs.fileInput.click()"
              >
                <img v-if="photoForm.imgUrl" :src="photoForm.imgUrl" class="upload-image">
                <i v-else class="el-icon-plus upload-icon"></i>
              </div>
              <div class="el-upload__tip">建议上传高质量的图片，JPG/PNG格式，大小不超过5MB</div>
            </div>
          </el-form-item>
          
          <el-form-item label="作品标题" prop="title">
            <el-input v-model="photoForm.title" placeholder="请输入作品标题"></el-input>
          </el-form-item>
          
          <el-form-item label="作品类型" prop="type">
            <el-radio-group v-model="photoForm.type">
              <el-radio :label="1">手机摄影</el-radio>
              <el-radio :label="2">相机摄影</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="作品描述" prop="description">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入作品描述，包括拍摄背景、创作理念等"
              v-model="photoForm.description">
            </el-input>
          </el-form-item>
          
          <el-form-item label="报名编号" prop="registrationNumber" v-if="registrationNumber">
            <el-input v-model="photoForm.registrationNumber" placeholder="报名编号" disabled></el-input>
            <div class="form-tip">报名编号已自动填写，无需修改</div>
          </el-form-item>
          
          <el-form-item label="报名编号" prop="registrationNumber" v-else>
            <el-input v-model="photoForm.registrationNumber" placeholder="请输入您的报名编号"></el-input>
            <div class="form-tip">如果您已报名，请输入报名编号关联您的参赛信息</div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitUpload" :loading="uploading">提交作品</el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <footer class="footer">
      <div class="footer-content">
        <p>© 2023 PhotoPro - 摄影作品管理与展示平台</p>
      </div>
    </footer>
  </div>
</template>

<script>
import Header from '@/components/Header.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'UploadPhoto',
  components: {
    Header
  },
  data() {
    return {
      registrationNumber: '',
      uploading: false,
      photoForm: {
        title: '',
        type: 1,
        description: '',
        imgUrl: '',
        registrationNumber: '',
        author: '',
        userId: null
      },
      photoRules: {
        title: [
          { required: true, message: '请输入作品标题', trigger: 'blur' },
          { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择作品类型', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入作品描述', trigger: 'blur' },
          { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
        ],
        registrationNumber: [
          { required: true, message: '请输入报名编号', trigger: 'blur' }
        ]
      },
      selectedFile: null
    }
  },
  computed: {
    ...mapGetters(['userId', 'nickname', 'isLogin'])
  },
  created() {
    // 从URL参数中获取报名编号
    const regNumber = this.$route.query.registrationNumber
    if (regNumber) {
      this.registrationNumber = regNumber
      this.photoForm.registrationNumber = regNumber
    }
    
    // 如果用户已登录，设置用户信息
    if (this.isLogin) {
      this.photoForm.userId = this.userId
      this.photoForm.author = this.nickname
    }
  },
  methods: {
    handleFileChange(e) {
      const file = e.target.files[0]
      if (!file) return
      
      // 验证文件类型和大小
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      
      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!')
        return
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return
      }
      
      this.selectedFile = file
      
      // 创建预览
      const reader = new FileReader()
      reader.onload = (event) => {
        this.photoForm.imgUrl = event.target.result
      }
      reader.readAsDataURL(file)
    },
    async submitUpload() {
      if (!this.selectedFile) {
        this.$message.warning('请上传作品图片')
        return
      }
      
      this.$refs.photoForm.validate(async valid => {
        if (valid) {
          this.uploading = true
          try {
            // 首先上传图片
            const formData = new FormData()
            formData.append('file', this.selectedFile)
            
            const uploadRes = await this.$http.post('/photos/upload', formData)
            if (uploadRes.data.code === 1) {
              // 图片上传成功，提交作品信息
              const photoData = {
                title: this.photoForm.title,
                type: this.photoForm.type,
                description: this.photoForm.description,
                imgUrl: uploadRes.data.data,
                registrationNumber: this.photoForm.registrationNumber,
                userId: this.photoForm.userId,
                author: this.photoForm.author || '匿名用户'
              }
              
              const res = await this.$http.post('/photos', photoData)
              if (res.data.code === 1) {
                this.$message.success('作品上传成功，请等待审核')
                this.resetForm()
                
                // 跳转到个人中心或首页
                if (this.isLogin) {
                  this.$router.push('/user/works')
                } else {
                  this.$router.push('/')
                }
              } else {
                this.$message.error(res.data.msg || '提交失败')
              }
            } else {
              this.$message.error(uploadRes.data.msg || '图片上传失败')
            }
          } catch (error) {
            console.error('上传作品失败', error)
            this.$message.error('上传失败，请稍后重试')
          } finally {
            this.uploading = false
          }
        }
      })
    },
    resetForm() {
      this.photoForm = {
        title: '',
        type: 1,
        description: '',
        imgUrl: '',
        registrationNumber: this.registrationNumber || '',
        author: this.nickname || '',
        userId: this.userId || null
      }
      this.selectedFile = null
      if (this.$refs.photoForm) {
        this.$refs.photoForm.resetFields()
      }
    },
    goToContest() {
      this.$router.push('/contest')
    },
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.upload-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
}

.container {
  max-width: 900px;
  margin: 40px auto;
  padding: 0 20px;
  flex: 1;
}

.upload-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.registration-label {
  float: right;
  color: #409EFF;
  font-size: 14px;
}

.registration-info {
  margin-bottom: 20px;
}

.upload-form {
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  margin-top: 4px;
}

.manual-upload {
  width: 100%;
  text-align: center;
}

.upload-box {
  width: 300px;
  height: 300px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  background-color: #fafafa;
}

.upload-box:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.el-upload__tip {
  line-height: 1.4;
  margin-top: 10px;
  color: #909399;
}

.upload-item {
  margin-bottom: 30px;
}

.footer {
  background-color: #34495e;
  color: white;
  padding: 20px 0;
  margin-top: 40px;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  text-align: center;
}

@media (max-width: 768px) {
  .upload-box {
    width: 250px;
    height: 250px;
  }
}
</style> 